package org.example.day08;

/**
 * 第三章节3.1.19.1: 多生产-多消费情况下的逻辑错误
 * 没搞懂
 */
//生产者
public class MyThread7 {
    private String lock;

    public MyThread7(String lock) {
        this.lock = lock;
    }

    public void setValue() {
        try {
            synchronized (lock) {
                while (!ValueObject2.value.equals("")) {
                    lock.wait();
                }
                String value = System.currentTimeMillis() + "_" + System.nanoTime();
                System.out.println("set的值是: " + value);
                ValueObject1.value = value;
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String lock = new String("");
        //生产者
        MyThread7 m7 = new MyThread7(lock);
        //消费者
        C2 c2 = new C2(lock);
        //生产者线程组
        Thread7A[] thread7AS = new Thread7A[20];
        //消费者线程组
        Thread7B[] thread7BS = new Thread7B[20];
        for (int i = 0; i < 20; i++) {
            thread7AS[i] = new Thread7A(m7);
            thread7AS[i].setName("生产者" + i + " **");
            thread7AS[i].start();
        }
        for (int i = 0; i < 2; i++) {
            thread7BS[i] = new Thread7B(c2);
            thread7BS[i].setName("消费者" + i);
            thread7BS[i].start();
        }
    }
}

class ValueObject2 {
    public static String value = "";
}

//消费者
class C2 {
    private String lock;

    public C2(String lock) {
        this.lock = lock;
    }

    public void getValue() {
        try {
            synchronized (lock) {
                while (ValueObject2.value.equals("")) {
                    lock.wait();
                }
                System.out.println("get的值是: " + ValueObject2.value);
                ValueObject2.value = "";
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//生产者线程
class Thread7A extends Thread {
    private MyThread7 m7;

    public Thread7A(MyThread7 m7) {
        this.m7 = m7;
    }

    @Override
    public void run() {
        while (true) {
            m7.setValue();
        }
    }
}

//消费者线程
class Thread7B extends Thread {
    private C2 c2;

    public Thread7B(C2 c2) {
        this.c2 = c2;
    }

    @Override
    public void run() {
        while (true) {
            c2.getValue();
        }
    }
}